package com.yan.qing.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @description: 解决ABA问题
 * @author: lf
 * @create: 2022年03月13日 23:35:00
 */
public class AtomicStampedReferenceResolveABA {
    private static AtomicInteger index=new AtomicInteger (10);
    static AtomicStampedReference<Integer> stampedReference= new AtomicStampedReference(10,1);

    //ABA问题
    public static void main (String[] args) {
        new Thread (()->{
            int stamp = stampedReference.getStamp ();
            System.out.println (Thread.currentThread ().getName () + "第一次版本" + stampedReference.getStamp ());
            stampedReference.compareAndSet (10,11,stampedReference.getStamp (),stampedReference.getStamp ()+1);
            System.out.println (Thread.currentThread ().getName () + "第二次版本" + stampedReference.getStamp ());
            stampedReference.compareAndSet (11,10,stampedReference.getStamp (),stampedReference.getStamp ()+1);
            System.out.println (Thread.currentThread ().getName () + "第三次版本" + stampedReference.getStamp ());
        },"张三").start ();
        new Thread (()->{
            try {
                int stamp = stampedReference.getStamp ();
                System.out.println (Thread.currentThread ().getName () + "第一次版本" + stampedReference.getStamp ());
                TimeUnit.SECONDS.sleep(2);
                boolean isSuccess = stampedReference.compareAndSet (10, 12,stampedReference.getStamp(),stampedReference.getStamp() + 1);
                System.out.println (Thread.currentThread ().getName () + "修改是否成功?" + isSuccess+"当前版本"+stampedReference.getStamp ());
                System.out.println (Thread.currentThread ().getName () + "当前的实际值" + stampedReference.getReference ());
            } catch ( InterruptedException e ) {
                e.printStackTrace ();
            }
        },"李四").start ();
    }
}